package com.zcl.Thread.t6;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/9  16:32
 *
 * 使用同步方法解决Thread类继承出现的线程安全问题
 *
 *
 */



class Ticket extends Thread {
    private static int ticket = 100;

    @Override
    public void run() {
        while (true){
            show();
        }
    }

    private static synchronized void show() { //synchronized ()同步监视器是this:当前对象-->thread1, thread2, thread3三个,所以无法使用这种方法
                                              //为了使多个线程共享一个同步监视器(使用同一把锁),故将方法变成静态方法,各个对象共享同一个方法
                                              //此时同步监视器不是this,而是Ticket.class类而不是对象
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName()+ ": 卖票,票号为: "+ ticket);
            ticket--;
        }
    }
}

public class TestTicket {

    public static void main(String[] args) {
        Ticket ticket1 = new Ticket();
        Ticket ticket2 = new Ticket();
        Ticket ticket3 = new Ticket();

        ticket1.setName("窗口1");
        ticket2.setName("窗口2");
        ticket3.setName("窗口3");

        ticket1.start();
        ticket2.start();
        ticket3.start();
    }


}
